package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description: 全局过滤器，
 * 目的是：校验JWT令牌并且解析令牌下放到各个微服务
 * @Version: V1.0
 */
@Component
@Slf4j
@Order(1)
public class AuthorizeFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1 获取request和response对象，获取请求url，登录请求则放行
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().getPath();
        if (url.contains("/login/in")) {
            // 放行
            return chain.filter(exchange);
        }

        //2 从header中获取token，判断token是否存在
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) { //拦截
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            //3 校验token
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int verifyToken = AppJwtUtil.verifyToken(claims);

            if (verifyToken > 0) {  // token 失效
                log.error("token is overdue, url:{}，claims：{}",url, claims);
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //4 解析token --> id 登录用户的id
            Integer id = claims.get("id", Integer.class);

            //5 id下放到各个微服务中 header
            ServerHttpRequest httpRequest = request.mutate()
                    .headers(httpHeaders -> {
                        httpHeaders.add("userId", id.toString());
                    }).build();
            exchange.mutate().request(httpRequest).build();

        } catch (Exception e) {
//            e.printStackTrace();
            log.error("verifyToken is error, url:{}",url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //6 放行
        return chain.filter(exchange);
    }
}
